# coding=utf-8
# cache_handle.py
from django.core.cache import cache




class Node(object):
    def __init__(self, obj):
        super(Node, self).__init__(obj)
        self.pk = obj.pk
        self.obj = obj
        self.node_type = self.__class__.__name__.lower()
        self.parent = None
        self.childs = []

        self.cache_key = '%s-cache-key-for-%s' % (self.node_type, self.pk)
        self.timeout = self.__get_timeout

    def __setattr__(self, attr, value):
        self.__dict__[attr] = value
        self.__update(attr, value)

    def __getattr__(self, attr):
        if attr in self.__dict__:
            return self.__dict__[attr]

        return getattr(self, attr)

    def __get_timeout(self, key):
        pass


    def has_child(self):
        return self.childs and True or False


    def count_sub_node(self, node_type='class'):
        if not self.node_type or self.childs:
            return 0
        elif self.node_type = node_type:
            return 1

        sum = 0
        for node in self.childs:
            sum += node.__count_sub_node(node_type)
        return sum


    def get_class_online(self):

        pass

    def get_teacher_online(self):
        pass

    def __update(self, key, value):
        cache_obj = cache.get(self.cache_key)
        if cache_obj and isinstance(cache_obj, str):
            cache_obj = json.loads(cache_obj)
        cache_obj.__dict__[key] = value
        cache.set(self.cache_key, value, self.timeout(key))


class Province(Node):
    pass

class City(Node):
    pass

class Country(Node):
    pass

class Town(Node):
    pass

class School(Node):
    pass

class Grade(Node):
    pass

class Klass(Node):
    def __init__(self, obj):
        super(Klass, self).__init__(obj)
        self.node_type = 'class'

    def is_computerclass(self):
        if self.obj.grade.number == 13:
            return True
        else:
            return False
    def is_reported(self):
        if self.reported:
            return True
        if self.obj.classmacv2_set.count():
            self.reported = True
            return True
        return False

    def set_not_reported(self):
        self.reported = False

    def set_class_online(self):
        self.is_active = True

    def set_teacher_online(self, teacher):
        pass


